/*
 * 存放查询条件中select标签的值，以select标签name为外层key，以option的value为内层key；
 * eg: selectTagMap = {status:{WU:'无'}}
 * 该对象用于匹配列表中状态等字段代码
 */
var selectTagMap = {};
$(function () {
    //获取所有select值
    $("select").each(function () {
        var optionMap = {};
        $(this).find("option").each(function (n, v) {
            optionMap[v.value] = v.text;
        });
        selectTagMap[this.name] = optionMap;
    });
    $("#distStatus").change(function () {
        if (this.value == 'UNDISTED') {
            $(".show-ctrl").show();
        } else {
            $(".show-ctrl").hide();
        }
    });
  //隐藏或展开查询条件
	$(".open-close").click(function(){
		var thiz = $(this).find("i");
		$("#searchForm").slideToggle(500,function(){
			if(thiz.attr("class") == "fa-chevron-up"){
				thiz.removeClass();
				thiz.addClass("fa-chevron-down");
			} else {
				thiz.removeClass();
				thiz.addClass("fa-chevron-up");
			}
		});
	});
    //初始化表格
    $("#contentTable").bootstrapTable($.fn.BTConfigSimple({
        pageSize: 20,
        pageList: [20, 100, 300, 500],
        sortName: "a.lastUpdated",
        sortOrder: "desc",
        userQuery: function () {
            return $('#searchForm').refreshByForm().query;
        }
    }));
    //初始化模态框
    $('#distModal').modal({
        backdrop: 'static',
        show: false,
        keyboard: false
    });
    //初始化模态框
    $('#groupModal').modal({
        backdrop: 'static',
        show: false,
        keyboard: false
    });
    //初始化模态框
    $('#batchEditModal').modal({
        backdrop: 'static',
        show: false,
        keyboard: false
    });
    //分配弹出框
    $("#aDist").click(function () {
        if (!$("#contentTable").bootstrapTable('getSelections').length) {
            alertx("请选择需要分配的数据！");
            return false;
        }
        $("#distPage").attr("src", $(this).data("url"));
        $("#distModal").modal("show");
        return false;
    });
    //分配
    $("#btnDist").click(function () {
        var dist_url = $(this).data("url");
        var userIds = window.frames[0].selectUser();
        if (!userIds || userIds.length == 0) {
            alertx("请选择需要分配的人员！");
            console.log("return false")
            return false;
        }
        console.log("btndist submit")
        var ids = $.map($("#contentTable").bootstrapTable('getSelections'), function (row) {
            return row.id;
        });
        $.ajax({
            url: dist_url,
            type: "POST",
            data: {userIds: userIds.join(','), ids: ids.join(',')},
            dataType: "json",
            success: function (data) {
                if (data.state) {
                    alertx(data.message, function () {
                        $("#distModal").modal("hide");
                        refreshTableData();
                    }, null, null, "info");
                } else {
                    alertx(data.message, function () {
                    }, null, null, "error");
                }
            },
            error: function () {
                alertx("发送请求失败，请稍后再试！", function () {
                    $("#distModal").modal("hide");
                    refreshTableData();
                }, null, null, "error");
            }
        });
    });

    //分组弹出框
    $("#aGroup").click(function () {
        if (!$("#contentTable").bootstrapTable('getSelections').length) {
            alertx("请选择需要分组的数据！");
            return false;
        }
        $("#groupPage").attr("src", $(this).data("url"));
        $("#groupModal").modal("show");
        return false;
    });

    //分组
    $("#btnGroup").click(function () {
        var group_url = $(this).data("url");
        var groupId = window.frames["groupPage"].selectGroup();
        if (!groupId) {
            alertx("请选择分组！");
            return false;
        }
        var ids = $.map($("#contentTable").bootstrapTable('getSelections'), function (row) {
            return row.id;
        });
        $.ajax({
            url: group_url,
            type: "POST",
            data: {groupId: groupId, ids: ids.join(',')},
            dataType: "json",
            success: function (data) {
                if (data.state) {
                    alertx(data.message, function () {
                        $("#groupModal").modal("hide");
                        refreshTableData();
                    }, null, null, "info");
                } else {
                    alertx(data.message, function () {
                        $("#groupModal").modal("hide");
                        refreshTableData();
                    }, null, null, "error");
                }
            },
            error: function () {
                alertx("发送请求失败，请稍后再试！", function () {
                    $("#groupModal").modal("hide");
                    refreshTableData();
                }, null, null, "error");
            }
        });
    });

    //合并弹出框
    $("#aMerge").click(function () {
        var selectRows = $("#contentTable").bootstrapTable('getSelections');
        if (!selectRows.length) {
            alertx("请选择需要合并的数据！");
            return false;
        } else if (selectRows.length == 1) {
            alertx("至少选择2条数据才能进行合并操作！");
            return false;
        }
        $("#mergeTable").bootstrapTable({
            pagination: false,
            rowStyle: {classes: 'list', height: 20}
        });
        $("#mergeModal").on("show", function () {
            $("#mergeTable").bootstrapTable('removeAll');
            $("#mergeTable").bootstrapTable('load', selectRows);
            $("#mergeTable").bootstrapTable('uncheckAll');
        });
        $("#mergeModal").modal("show");
        return false;
    });

    //合并
    $("#btnMerge").click(function () {
        var merge_url = $(this).data("url");
        var id = $("#mergeTable").bootstrapTable('getSelections')[0].id;
        var allData = $("#mergeTable").bootstrapTable('getData');
        var ids = new Array(),mergerNum = 0,noReadMergerNum = 0 ;
        for ( var i = 0 ; i < allData.length ; i ++ ) {
            var _data = allData[i];
            ids.push(_data.id);
            mergerNum += _data.mergerNum;//统计合并数量
            noReadMergerNum += _data.noReadMergerNum;//统计未读数量
        }
        mergerNum = mergerNum + (allData.length -1);//加上被合并的数据条数
        ids.splice(ids.indexOf(id), 1);  //去掉选择的ID
        $.ajax({
            url: merge_url,
            type: "POST",
            data : {id: id,mergerNum: mergerNum,noReadMergerNum: noReadMergerNum,ids: ids.join(',')},
            dataType: "json",
            success: function (data) {
                if (data.state) {
                    alertx(data.message, function () {
                        $("#mergeModal").modal("hide");
                        refreshTableData();
                    }, null, null, "info");
                } else {
                    alertx(data.message, function () {
                        $("#mergeModal").modal("hide");
                        refreshTableData();
                    }, null, null, "error");
                }
            },
            error: function () {
                alertx("发送请求失败，请稍后再试！", function () {
                    $("#mergeModal").modal("hide");
                    refreshTableData();
                }, null, null, "error");
            }
        });
    });


    // 一键结束
    $("#oneKeyClose").click(function(){
        var _this = $(this);
        confirmx("您确定结束符合结束条件但未结束的数据?",function(){
            $.post($(_this).data("url"),function(){
               window.location.reload();
            });
        });
    });

    // 一键结束全部
    $("#oneKeyCloseAll").click(function(){
        var _this = $(this);
        confirmx("您确定结束符合您和您管理的操作员中符合结束条件但未结束的数据?",function(){
            $.post($(_this).data("url"),function(){
                window.location.reload();
            });
        });
    });

});

function addSalesInfo(salesData, salesUrl) {
    var result = null;
    $.ajax({
        url: salesUrl,
        type: "POST",
        data: salesData,
        async: false,
        dataType: "json",
        success: function (data) {
            result = data;
        },
        error: function () {
            var data = {};
            data.state = false;
            data.message = "发送请求失败，请稍后再试！";
            result = data;
        }
    });
    return result;
}



function refreshTableData() {
    $("#contentTable").bootstrapTable('refresh', $('#searchForm').refreshByForm());
}

function corporationNameFormatter(value, row, index) {
    return "<a  class='addTab'  href='" + ctx + "/mywork/potentialCustomer/detail?id=" + row.id
           + "' target='mainFrame'>" + value + "</a>";
}

function dataStatusFormatter(value, row, index) {
    return row.mergerNum + "（<font color='red'>" + row.noReadMergerNum + "</font>）";
}

function targetProductsFormatter(value, row, index) {
    return selectTagMap["targetProducts"][value];
}

function visitNumFormatter(value, row, index) {
    if (row.visitNum) {
        return "是";
    } else {
        return "否";
    }
}


